﻿@using Microsoft.Extensions.Configuration;
@implements IAsyncDisposable
@inject IJSRuntime JS
@inject IConfiguration config

<div id="@ContainerId" style="@Style"></div>

@code {

    /// <summary>
    /// BaiduKey<para></para>
    /// 为空则在 IConfiguration 服务获取 "BaiduKey" , 默认在 appsettings.json 文件配置
    /// </summary>
    [Parameter]
    public string? Key { get; set; }

    /// <summary>
    /// 定位结果回调方法
    /// </summary>
    [Parameter]
    public Func<BaiduLocation, Task>? OnResult { get; set; }

    /// <summary>
    /// 容器控件style
    /// </summary>
    public string Style { get; set; } = "height:400px;width:100%;";

    /// <summary>
    /// 容器控件ID
    /// </summary>
    public string ContainerId { get; set; } = "container";

    private IJSObjectReference? module;
    private DotNetObjectReference<BaiduMap>? InstanceGeo { get; set; }

    //百度地图秘钥
    private string key = String.Empty;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            //在 IConfiguration 服务获取 "BaiduKey" , 默认在 appsettings.json 文件配置
            key = Key ?? config["BaiduKey"];

            module = await JS.InvokeAsync<IJSObjectReference>("import", "./js/baidumap.js");
            InstanceGeo = DotNetObjectReference.Create(this);
            while (!(await InitMapScript()))
            {
                await Task.Delay(500);
            }
        }
    }

    //初始化百度地图api的js
    public async Task<bool> InitMapScript() => await module!.InvokeAsync<bool>("addScript", new object?[] { key, ContainerId, InstanceGeo, null, null });

    /// <summary>
    /// 定位完成回调方法
    /// </summary>
    /// <param name="geolocations"></param>
    /// <returns></returns>
    [JSInvokable]
    public async Task GetResult(BaiduLocation geolocations)
    {
        await OnResult?.Invoke(geolocations);

        string json = JsonSerializer.Serialize(geolocations);
        System.Diagnostics.Debug.WriteLine(json);
    }

    async ValueTask IAsyncDisposable.DisposeAsync()
    {
        if (module is not null)
        {
            await module.DisposeAsync();
        }
    }
}

